package com.sqx.modules.health.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sqx.modules.app.utils.JwtUtils;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.config.RemoteConfig;
import com.sqx.modules.health.entity.*;
import com.sqx.modules.health.service.*;
import com.sqx.modules.health.utils.DateUtil;
import com.sqx.modules.health.utils.Remote;
import com.sqx.modules.sys.entity.SysUserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Api(value = "app端数据相关接口	", tags = "app端数据相关接口", description = "")
@RestController
@RequestMapping("/health/app")
public class AppPatientController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IRecordService recordService;
    @Autowired
    private IAppPatientService appPatientService;
    @Autowired
    private ISurveyrecordService surveyrecordService;
    @Autowired
    private IAppProductService appProductService;
    @Autowired
    private NcgWatchService ncgWatchService;
    @Autowired
    private INcgDeviceWatchService ncgDeviceWatchService;

    @Autowired
    private JwtUtils jwtUtils;

    private String switchKinsfolk(String uid) {

        return "";
    }

    /**
     * 获取血糖趋势
     *
     * @return
     */
    @ApiOperation(value = "获取血糖视图趋势")
    @PostMapping("/getChartData")
    public Result getChartData(@RequestParam Map<String, String> params) throws ParseException {
        String currDataUid = params.get("currDataUid");
        // 1 血糖  2 血压  8 血脂  6尿酸
        String type = params.get("type");
        String days = "7";
        if (StrUtil.isBlank(currDataUid) || StrUtil.isBlank(type)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        String uid = currDataUid;
        //获取数据 统计
        Date now = new Date();
        String endDate = DateUtil.parseStr(now, DateUtil.FMT_YYYYMMDD_HHMMSS);
        String startDate = DateUtil.parseStr(DateUtil.addDays(now, -(Integer.parseInt(days) - 1)), DateUtil.FMT_YYYYMMDD_HHMMSS);
        QueryWrapper<Record> rm = new QueryWrapper<Record>()
                .eq(ObjectUtil.isNotEmpty(uid), "uid", uid)
                .eq("type", type)
                .eq("flag", 1) // 黄劲博
                //.between(ObjectUtil.isNotEmpty(days),"recordtime",startDate,endDate)
                .ge("recordtime", startDate)
                .le("recordtime", endDate)
                .orderByAsc("recordtime");
        List<Record> records = recordService.list(rm);
        return Result.success(appPatientService.getChartDataJSONObject(records, type,startDate,endDate));
    }


    //-------------------------------------------------血糖区域------------type=1----------------------------------------------

    /**
     * 获取血糖总览数据
     *
     * @return
     */
    @ApiOperation(value = "获取血糖总览数据")
    @PostMapping("/getSuggerView")
    public Result getSuggerView(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String currDataUid = params.get("currDataUid");
        if (StrUtil.isBlank(token) || StrUtil.isBlank(currDataUid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uid", currDataUid);
        jsonObject.put("type", 1);
        //数据 统计
        JSONObject reJson = appPatientService.getSuggerData(jsonObject);
        return Result.success(reJson);
    }

    /**
     * 获取血糖趋势
     *
     * @return
     */
    @ApiOperation(value = "获取血糖视图趋势")
    @PostMapping("/getSuggerChart")
    public Result getSuggerChart(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String days = params.get("days");
        String currDataUid = params.get("currDataUid");
        if (StrUtil.isBlank(token) || StrUtil.isBlank(days) || StrUtil.isBlank(currDataUid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uid", currDataUid);
        jsonObject.put("type", 1);

        //获取数据 统计
        Date now = new Date();
        String endDate = DateUtil.parseStr(now, DateUtil.FMT_YYYYMMDD) + " 23:59:59";
        String startDate = DateUtil.parseStr(DateUtil.addDays(now, -Integer.valueOf(days)), DateUtil.FMT_YYYYMMDD) + " 00:00:00";
        QueryWrapper<Record> rm = new QueryWrapper<Record>()
                .eq(ObjectUtil.isNotEmpty(uid), "uid", jsonObject.get("uid"))
                .eq("type", jsonObject.get("type"))
                .eq("flag", 1) // 黄劲博
                //.between(ObjectUtil.isNotEmpty(days),"recordtime",startDate,endDate)
                .ge("recordtime", startDate)
                .le("recordtime", endDate)
                .orderByDesc("recordtime");
        List<Record> records = recordService.list(rm);
        JSONObject reJson = appPatientService.getSuggertrend(records);
        return Result.success(reJson);
    }

    /**
     * 获取血糖基础数据
     *
     * @return
     */
    @ApiOperation(value = "获取血糖基础数据")
    @PostMapping("/getSuggerTable")
    public Result getSuggerTable(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String currDataUid = params.get("currDataUid");
        if (StrUtil.isBlank(token) || StrUtil.isBlank(currDataUid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uid", currDataUid);
        //jsonObject.put("days",days);
        jsonObject.put("type", 1);

        //数据 统计
        JSONArray reJson = appPatientService.getSuggerTable(jsonObject);
//        JSONObject reJson = appPatientService.getSuggerTable(jsonObject);
        return Result.success(reJson);
    }

//-------------------------------------------------血压区域----------------type=2------------------------------------------

    /**
     * 获取血压总览数据
     *
     * @return
     */
    @PostMapping("/getPressureView")
    @ApiOperation(value = "获取血压总览数据")
    public Result getPressureView(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String currDataUid = params.get("currDataUid");
        if (StrUtil.isBlank(token) || StrUtil.isBlank(currDataUid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uid", currDataUid);
        jsonObject.put("type", 2);
        //数据 统计
        JSONObject reJson = appPatientService.getPressureData(jsonObject);
        return Result.success(reJson);
    }

    /**
     * 获取血压总览视图趋势
     *
     * @return
     */
    @PostMapping("/getPressureChart")
    @ApiOperation(value = "获取血压视图趋势")
    public Result getPressureChart(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String days = params.get("days");
        String currDataUid = params.get("currDataUid");
        if (StrUtil.isBlank(token) || StrUtil.isBlank(days) || StrUtil.isBlank(currDataUid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uid", currDataUid);
        jsonObject.put("type", 2);
        //获取数据 日期统一用字符串  yyyy-MM-dd HH:mm:ss
        Date now = new Date();
        String endDate = DateUtil.parseStr(now, DateUtil.FMT_YYYYMMDD_HHMMSS);
        String startDate = DateUtil.parseStr(DateUtil.addDays(now, -Integer.valueOf(days)), DateUtil.FMT_YYYYMMDD_HHMMSS);
        ;
        QueryWrapper<Record> rm = new QueryWrapper<Record>()
                .eq(ObjectUtil.isNotEmpty(uid), "uid", jsonObject.get("uid"))
                .eq("type", jsonObject.get("type"))//血压1
                .eq("flag", 1) // 黄劲博
                //.between(ObjectUtil.isNotEmpty(days),"recordtime",startDate,endDate)
                .ge("recordtime", startDate)
                .le("recordtime", endDate)
                .orderByDesc("recordtime");
        List<Record> rRecord = recordService.list(rm);
        return Result.success(appPatientService.getPressuretrend(rRecord));
    }

    /**
     * 获取血压基础数据
     *
     * @return
     */
    @ApiOperation(value = "获取血压基础数据")
    @PostMapping("/getPressureTable")
    public Result getPressureTable(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String currDataUid = params.get("currDataUid");
        if (StrUtil.isBlank(token) || StrUtil.isBlank(currDataUid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);
        QueryWrapper<Record> rm = new QueryWrapper<Record>()
                .eq("uid", currDataUid)
                .eq("type", 2)
                .eq("flag", 1) // 黄劲博
                .orderByDesc("recordtime");
        List<Record> glucoseList = recordService.list(rm);
        SimpleDateFormat aaDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        glucoseList.forEach(one -> {
            if (ObjectUtil.isNotEmpty(one.getRecordtime())) {
                Date date = null;
                try {
                    date = aaDateFormat.parse(one.getRecordtime());
                    String aabb = DateUtil.parseStr(date, DateUtil.FMT_YYYYMMDD);
                    one.setRecordtime(aabb);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        return Result.success(glucoseList);

    }


    //--------------------------------------------动态血压 和动态心电数据---------------------------------------------------------------------

    /**
     * 获取动态血压数据
     *
     * @return
     */
    @ApiOperation(value = "获取动态血压基础数据")
    @PostMapping("/getDynaData")
    public Result getDynaData(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String currDataUid = params.get("currDataUid");
        if (StrUtil.isBlank(token) || StrUtil.isBlank(currDataUid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        ////String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);
        QueryWrapper<Record> rm = new QueryWrapper<Record>()
                .eq("uid", currDataUid)
                .eq("type", 3)
                .orderByDesc("recordtime");
        List<Record> glucoseList = recordService.list(rm);
        SimpleDateFormat aaDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        glucoseList.forEach(one -> {
            if (ObjectUtil.isNotEmpty(one.getRecordtime())) {
                one.setRecordtime(one.getRecordtime().split(" ")[0].substring(5).replace("-", "/"));
//                Date date = null;
//                try {
//                    date = aaDateFormat.parse(one.getRecordtime().re);
//                    String aabb = DateUtil.parseStr(date,DateUtil.FMT_YYYYMMDD);
//                    one.setRecordtime(one.getRecordtime().replace("-","/"));
//                } catch (ParseException e) {
//                    throw new RuntimeException(e);
//                }
            }
            if (ObjectUtil.isNotEmpty(one.getDoctorid())) {
                SysUserEntity user = userService.getRedisByUid(one.getDoctorid() + "");
                if (ObjectUtil.isNull(user)) user.setUsername("医生姓名");
                one.setDoctorname(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName());
            }
        });

        return Result.success(glucoseList);
    }

    @ApiOperation(value = "获取动态血压分条记录详情")
    @PostMapping("/getDynaPressureData")
    public Result getDynaPressureData(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String patid = params.get("patid");
        String currDataUid = params.get("currDataUid");
        if (StrUtil.isBlank(token) || StrUtil.isBlank(currDataUid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
//        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);
        QueryWrapper<Surveyrecord> queryWrapper = new QueryWrapper<Surveyrecord>()
                .eq(ObjectUtil.isNotEmpty(patid), "patid", patid)
                .orderByDesc("sampleDate");
        List<Surveyrecord> glucoseList = surveyrecordService.list(queryWrapper);
        glucoseList.forEach(one -> {
            DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm:ss");
            String timeStr = df.format(one.getSampleDate().atZone(ZoneId.systemDefault()));
//            one.setSampleDateStr(timeStr);
        });
        return Result.success(glucoseList);
    }

    /**
     * 获取动态心电数据
     *
     * @return
     */
    @ApiOperation(value = "获取动态心电基础数据")
    @PostMapping("/getDyxdData")
    public Result getDyxdData(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String currDataUid = params.get("currDataUid");
        if (StrUtil.isBlank(token) || StrUtil.isBlank(currDataUid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);
        QueryWrapper<Record> rm = new QueryWrapper<Record>()
                .eq("uid", currDataUid)
                .eq("type", 4)
                .orderByDesc("recordtime");
        List<Record> glucoseList = recordService.list(rm);
        SimpleDateFormat aaDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        glucoseList.forEach(one -> {
            if (ObjectUtil.isNotEmpty(one.getRecordtime())) {
//                Date date = null;
//                try {
//                    date = aaDateFormat.parse(one.getRecordtime());
//                    String aabb = DateUtil.parseStr(date,DateUtil.FMT_YYYYMMDD);
//                    one.setRecordtime(aabb);
//                } catch (ParseException e) {
//                    throw new RuntimeException(e);
//                }
                one.setRecordtime(one.getRecordtime().split(" ")[0].substring(5).replace("-", "/"));
            }
            if (ObjectUtil.isNotEmpty(one.getDoctorid())) {
                SysUserEntity user = userService.getRedisByUid(one.getDoctorid());
                if (ObjectUtil.isNull(user)) user.setUsername("医生姓名");
                one.setDoctorname(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName());
            }
        });

        return Result.success(glucoseList);
    }


    // 条件查询
    @ApiOperation(value = "获取手表数据", notes = "获取手表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", paramType = "String"),
    })
    @PostMapping("/getPatWatchData")
    public Result getPatWatchData(@RequestParam Map<String, String> params) {

        String token = params.get("token");

        String currDataUid = params.get("currDataUid");
        if (StrUtil.isBlank(token) || StrUtil.isBlank(currDataUid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);

        QueryWrapper<NcgDeviceWatch> uidWrapper = new QueryWrapper<NcgDeviceWatch>()
                .eq(ObjectUtil.isNotEmpty(uid), "uid", currDataUid)
                .eq("type", 5);
        NcgDeviceWatch deviceWatch = ncgDeviceWatchService.getOne(uidWrapper);

        if (deviceWatch == null) {

            return Result.error(Constants.CODE_500, "未绑定手表设备");

        } else {

            String imei = deviceWatch.getImei();

            QueryWrapper<NcgWatch> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("imei,ifnull(sum(step_count),0) as stepCount,ifnull(sum(remain_electricity),0) as remainElectricity,ifnull(sum(systolic_blood_pressure),0) as systolicBloodPressure,ifnull(sum(diastolic_blood_pressure),0) as diastolicBloodPressure,ifnull(sum(heart_rate),0) as heartRate,ifnull(sum(blood_oxygen),0) as bloodOxygen,ifnull(sum(body_temperature),0) as bodyTemperature,createtime");
            queryWrapper.eq(ObjectUtil.isNotEmpty(imei), "imei", imei);
            queryWrapper.groupBy("createtime");
            List<NcgWatch> getData = (List<NcgWatch>) ncgWatchService.list(queryWrapper);
            List<NcgWatch> getDatanew = new ArrayList<>();
            for (int i = 0; i < getData.size(); i++) {
                NcgWatch one = getData.get(i);
//                one.getCreatetime().toString().split(" ")[0].substring(5).replace("-","/");
//                one.setCreatetime(one.getCreatetime().toString().split(" ")[0].substring(5).replace("-","/"));
//                one.put("pdtime",record.getRecordtime().substring(5,10).replace("-","/"));//日期2022-07-14 19:34:44
//                one.setCreatetime(one.getCreatetime().substring(5,10).replace("-","/"));
                if (one.getStepCount() > 0
                        || one.getBloodOxygen() > 0
                        || one.getDiastolicBloodPressure() > 0
                        || one.getSystolicBloodPressure() > 0
                        || one.getHeartRate() > 0
                        || one.getBodyTemperature().doubleValue() > 0
                ) {
                    getDatanew.add(one);
                }
            }
            Collections.sort(getDatanew, Comparator.comparing(NcgWatch::getCreatetime).reversed());

            return Result.success(getDatanew);
        }
    }


    @ApiOperation(value = "App患者端产品列表")
    @PostMapping("/productList")
    public Result productList(@RequestParam Map<String, String> params) {

        QueryWrapper<AppProduct> rm = new QueryWrapper<AppProduct>()
                .eq("isshow", 1);
        List<AppProduct> glucoseList = appProductService.list(rm);

        return Result.success(glucoseList);
    }

    @ApiOperation(value = "App患者端产品详情")
    @PostMapping("/productDetail")
    public Result productDetail(@RequestParam Map<String, String> params) {

        String productid = params.get("productid");
        if (StrUtil.isBlank(productid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        AppProduct oneproduct = appProductService.getById(productid);
        return Result.success(oneproduct);
    }

    /**
     * 推送基础数据给医院
     *
     * @return Result
     */
    @ApiOperation(value = "推送基础数据给医院")
    @PostMapping("/postOutsideData")
    public Result postOutsideData(@RequestParam Map<String, String> params) {

//        Timestamp createTime1 = new Timestamp(new java.util.Date().getTime());
        Long createTime1 = new Date().getTime() / 1000;
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("hospitalid", "721AE68975F4AD2252DE5C12EE07B2D2");
        jsonBody.put("action", "BP");//BP血压，BG血糖
        JSONArray jsonData = new JSONArray();

        JSONObject jsonOne = new JSONObject();
        jsonOne.put("deviceId", "DEVICE_ID"); //设备id
        jsonOne.put("testId", createTime1);//检测id，用于数据去重，非必须，没有时，使用timestamp
        jsonOne.put("userId", "411328198003180032");//患者身份证号
        jsonOne.put("userName", "孟庆华");//患者姓名
        jsonOne.put("timestamp", createTime1);
        if (jsonBody.getString("action").equals("BP")) {
            jsonOne.put("dbp", 95);//舒张压 action=BP
            jsonOne.put("sbp", 165);//收缩压 action=BP
            jsonOne.put("hr", 99);//心率 action=BP
        } else if (jsonBody.getString("action").equals("BG")) {
            jsonOne.put("timeType", 1);//测试时间段：1为早餐前空腹，0为其他    action=BG
            jsonOne.put("sugar", 7);//血糖值  action=BG
        }
        jsonData.add(jsonOne);

        jsonBody.put("data", jsonData);
        JSONObject jsonRe = Remote.sendPatAPI(RemoteConfig.deviceDataUrl, new JSONObject(), jsonBody);

        return Result.success(jsonRe);
    }

    @ApiOperation(value = "获取动态血压基础数据")
    @PostMapping("/getIndexData")
    public Result getIndexData(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String currDataUid = params.get("currDataUid");
        String type = params.get("type");

        if (StrUtil.isBlank(token) || StrUtil.isBlank(currDataUid) || StrUtil.isBlank(type)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        QueryWrapper<Record> rm = new QueryWrapper<Record>()
                .eq("uid", currDataUid)
                .eq("type", type)
                .orderByDesc("recordtime");
        List<Record> glucoseList = recordService.list(rm);
        glucoseList.forEach(one -> {
            if (ObjectUtil.isNotEmpty(one.getRecordtime())) {
                one.setRecordtime(one.getRecordtime().split(" ")[0]);
            }
        });
        return Result.success(glucoseList);
    }


}
